package com.lee.springboot.service;

import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author lihaiqiang
 * @date 2021/7/6
 */
@Service
public class UserService {

    private ScheduledExecutorService scheduledExecutorService;
    private int i = 0;
    private int j = 0;

    public UserService() {
        System.out.printf("%tT [%s]: 执行构造函数%n", System.currentTimeMillis(), UserService.class.getName());
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.printf("定时: %tT, %s%n", System.currentTimeMillis(), i++);
            }
        }, 0, 2, TimeUnit.SECONDS);
    }

    /**
     * 初始化
     */
    @PostConstruct
    public void init() {
        System.out.printf("%tT [%s]: 我先干点啥事呢...？%n", System.currentTimeMillis(), UserService.class.getName());
    }

    /**
     * 优雅退出
     */
    @PreDestroy
    public void destroy() {
        System.out.printf("%tT [%s]收到进程终止信号，稍等，我溜达一会......%n", System.currentTimeMillis(), UserService.class.getName());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("%tT [%s]溜达结束，该干嘛干嘛去%n", System.currentTimeMillis(), UserService.class.getName());
    }

}
